<template>
    <span class="bind-account-btn" @click="handleVisible(true)" v-if="btnVisible">
        <!-- 自定义选择商品按钮 -->
        <slot name="btn">
            <el-button link type="primary" :disabled="disabled">已有账号，立即绑定</el-button>
        </slot>
    </span>
    <el-dialog
        class="bind-account-dialog"
        align-center
        title="绑定宝户通账号"
        v-model="visible"
        width="40%"
        :close-on-click-modal="false"
        @close="closeCallback()">
        <el-form :model="form" ref="formRef" label-width="auto" :rules="rules" @submit.prevent>
            <el-form-item prop="loginNo" label="登录号">
                <el-input
                    v-model.trim="form.loginNo"
                    placeholder="请输入宝户通的登录号"
                    @input="handleInput"></el-input>
            </el-form-item>
            <el-form-item label="账户名称">
                <div class="account-name" v-if="!isOpenSuceess">根据登录号自动获取</div>
                <div class="account-name" v-if="isOpenSuceess == 1">{{ accountName }}</div>
                <div class="account-disable" v-if="isOpenSuceess == 2">该账户尚未开户成功</div>
            </el-form-item>
            <el-form-item v-if="[1, 2].includes(accountType)" prop="certificateNo" label="社会信用代码">
                <el-input v-model.trim="form.certificateNo" placeholder="请输入被绑定账号的统一社会信用代码"></el-input>
            </el-form-item>
            <el-form-item v-if="[3].includes(accountType)" prop="certificateNo" label="身份证号">
                <el-input v-model.trim="form.certificateNo" placeholder="请输入被绑定账号的身份证号"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="custom-footer">
                <div>
                    <el-button plain @click="handleVisible(false)">取消</el-button>
                    <el-button type="primary" :disabled="isOpenSuceess != 1" @click="handleConfirm">确认</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, unref, computed } from 'vue';
import { cloneDeep, getRegExp } from '@/commons/utils';
import { debounce } from 'lodash';
import { ElMessageBox, ElMessage } from 'element-plus';
import request from '@/request';
import storage from '@/commons/storage';

/* ---------------------------------- 父级通信 start ---------------------------------- */
const emit = defineEmits(['handle-confirm']);
const props = defineProps({
    // 是否显示控制按钮
    btnVisible: {
        type: Boolean,
        default: true
    },
    // 是否禁用
    disabled: {
        type: Boolean,
        default: false
    }
});
/* ---------------------------------- 父级通信 end ---------------------------------- */

/* ---------------------------------- 弹窗表单 start ---------------------------------- */
const form = reactive({ loginNo: null, certificateNo: null }); // 表单
const formClone = cloneDeep(form); // 表单备份
const formRef = ref();
const rules = computed(() => {
    const ruleList = {
        loginNo: [{ required: true, message: '请输入登录号', trigger: 'blur' }]
    };
    if ([1, 2].includes(accountType.value)) {
        ruleList.certificateNo = [
            { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
            { pattern: getRegExp('creditCode'), message: '统一社会信用代码格式不正确', trigger: 'blur' }
        ];
    } else if ([3].includes(accountType.value)) {
        ruleList.certificateNo = [
            { required: true, message: '请输入身份证号', trigger: 'blur' },
            { pattern: getRegExp('idcard'), message: '身份证号格式不正确', trigger: 'blur' }
        ];
    }
    return ruleList;
}); // 表单验证规则

let accountName = ref(''); // 账户名称
let isOpenSuceess = ref(1); //账号是否开户成功 1是 2否
let accountType = ref(); //账号类型 1 企业账户 2 个体账户 3 个人账户'
let paySequenceNo = ref();
const handleInput = debounce(async () => {
    // 请求接口获取accountName
    if (!form.loginNo) {
        isOpenSuceess.value = null;
        accountName.value = '';
        accountType.value = null;
        paySequenceNo.value = null;
        return;
    }
    // 请求接口获取accountName
    try {
        const { data, code } = await request('accountLoginNo', { loginNo: form.loginNo });
        if ([0, 200].includes(code)) {
            isOpenSuceess.value = data.isOpenAccountSucceed;
            accountName.value = data.merchantName;
            accountType.value = data.accountType;
            paySequenceNo.value = data.paySequenceNo;
        } else {
            // 获取账户名称失败...
            isOpenSuceess.value = 2;
        }
    } catch (err) {
        // 获取账户名称失败...
        isOpenSuceess.value = 2;
    }
}, 500);
/* ---------------------------------- 弹窗表单 end ---------------------------------- */

/* ---------------------------------- 控制弹窗 start ---------------------------------- */
let loading = ref(false);
let visible = ref(false); // 弹窗展示隐藏
// 展示隐藏
const handleVisible = (isVisible = false) => {
    if (props.disabled) {
        return;
    }
    accountName.value = ''; // 重置账户名称
    isOpenSuceess.value = null;
    accountType.value = null;
    paySequenceNo.value = null;
    visible.value = isVisible;
    clearValidate();
};

// 重置验证
const resetFields = () => {
    unref(formRef)?.resetFields();
};
// 清空验证
const clearValidate = field => {
    unref(formRef)?.clearValidate(field);
};
// 校验验证
const validateField = field => {
    unref(formRef)?.validateField(field);
};
// 确认按钮
const handleConfirm = async () => {
    // 表单验证
    unref(formRef)?.validate(valid => {
        if (valid) {
            if (isOpenSuceess.value == 1) {
                ElMessageBox.confirm('确定绑定吗?', '提示', {
                    customClass: 'custom-box-confirm-class',
                    center: true,
                    type: 'none'
                }).then(async () => {
                    await request('loginBind', {
                        ...form,
                        paySequenceNo: paySequenceNo.value,
                        shopId: storage.get('ZW-SHOPID')
                    });
                    ElMessage.success('绑定成功');
                    emit('handle-confirm');
                    handleVisible(false);
                });
            }
        }
    });
};
// 关闭后重置表单
const closeCallback = visible => {
    resetFields();
    Object.assign(form, cloneDeep(formClone));
};

// 打开弹窗
const handleOpen = () => {
    handleVisible(true);
};

defineExpose({ handleOpen });

/* ---------------------------------- 控制弹窗 end ---------------------------------- */
</script>

<style lang="scss">
.bind-account {
    &-dialog {
        max-width: 600px;
        min-width: 600px;
        .el-dialog__body {
            padding-top: 35px !important;
            padding-right: 60px !important;
        }
        .account-name {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #888888;
        }
        .account-disable {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #fe292b;
        }
    }
    &-btn {
        display: inline-flex;
        .el-button.is-link {
            padding: 0;
            &:hover,
            &:focus {
                border-color: transparent !important;
                background-color: transparent !important;
            }
            &:hover {
                color: var(--el-button-hover-link-text-color) !important;
            }
        }
    }
}
.custom-box-confirm-class {
    width: 300px;
    .el-message-box__title {
        justify-content: flex-start;
    }
    .el-message-box__message {
        margin: 20px 0;
        font-size: 16px;
    }
    .el-button {
        width: 100px;
        margin-bottom: 10px;
    }
}
</style>
<style lang="scss" scoped></style>
